package br.ufmg.ubicomp.droidguide.eventservice;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Logger;


public class PeriodicTasksManager {
    private static final int NUM_MILLISECONDS_IN_SECOND = 1000;
    private boolean stop;
    private int numWarningBeeps;
    private static PeriodicTasksManager taskManager;
    
    private List<DroidGuideTask> tasks;
    private List<Boolean> stops;
    
    public static PeriodicTasksManager getInstance()
    {
    	if (taskManager == null)
    	{
    		taskManager = new PeriodicTasksManager();
    	}
    	return taskManager;
    }
    
    private PeriodicTasksManager() {
    	tasks = new ArrayList<DroidGuideTask>();
    	stops = new ArrayList<Boolean>();
    }

    public void schedule(TimerTask task, String name, long period)
    {
    	DroidGuideTask dgTask = new DroidGuideTask(name, task);
    	dgTask.schedule(task, 0, period*NUM_MILLISECONDS_IN_SECOND);
    	tasks.add(dgTask);
    }
    
    public void schedule(TimerTask task, String name, Date time)
    {
    	DroidGuideTask dgTask = new DroidGuideTask(name, task);
    	dgTask.schedule(task, time);
    	tasks.add(dgTask);
    }
    
    public void cancelAllTasks()
    {
    	for (DroidGuideTask t:tasks)
    	{
    		t.cancel();
    	}
    }
    
    public void stopTask(String name)
    {
    	for (DroidGuideTask t:tasks)
    	{
    		if (t.getName().equals(name))
    		{
    			t.cancel();
    			Logger logger = Logger.getLogger(this.getClass().getSimpleName());
    			logger.info("Task " + name + " canceled successfully.");
    		}
    	}
    }
    
    class RemindTask extends TimerTask {
        //int numWarningBeeps = 3;
        public void run() {
            if (!stop) {
                System.out.println(getStringDateTime() + " - Timer");
                numWarningBeeps--;
            } else {
                System.out.println(getStringDateTime() + " - Time's up!");
                //timer.cancel(); // Not necessary because
                                  // we call System.exit
                System.exit(0);   // Stops the AWT thread 
                                  // (and everything else)
            }
        }
		private String getStringDateTime() {
			Calendar dateTime = Calendar.getInstance();
			return new SimpleDateFormat("yyyy/MM/dd hh:mm:ssss").format(dateTime.getTime());
		}
    }
    
    public static void main(String[] args) {
		PeriodicTasksManager beep = new PeriodicTasksManager();
		
	}

	public List<DroidGuideTask> getTasks() {
		return tasks;
	}   
    
}